package com.lynx.core;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
 * 
 * @author lxp
 *
 */
public class ReadMapping {
	private static Map<String, String> mappings = new HashMap<String, String>();

	public static String geturlMapping(String key, String path) {
		String value = "";
		if (mappings.containsKey(key)) {
			value = (String) mappings.get(key);
		} else {
			File f = new File(path);
			DocumentBuilderFactory factory = DocumentBuilderFactory
					.newInstance();
			try {
				DocumentBuilder builder = factory.newDocumentBuilder();
				Document doc = builder.parse(f);
				NodeList nl = doc.getElementsByTagName("servlet-mapping");
				if (nl == null) {
					return "";
				}
				for (int i = 0; i < nl.getLength(); i++) {
					Node node = nl.item(i);
					value = node.getTextContent().replaceAll(key, "").trim();
				}
			} catch (ParserConfigurationException e) {
				e.printStackTrace();
			} catch (SAXException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			if (value.indexOf(".") != -1)
				value = value.substring(value.indexOf("."));
			else if (value.indexOf("/") != -1) {
				value = value.substring(value.indexOf("/"));
			}
			mappings.put(key, value);
		}
		return value;
	}
}